﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.IO;
using System.Windows.Forms;

namespace Red_Mosquito
{
    class Mosquito
    {
        String url, title, artist;
        Form1 form;

        public Mosquito(Form1 f)
        {
            form = f;
        }

        public void search(String p_title, String p_artist)
        {
            title = p_title;
            artist = p_artist;

            // Build URL using title, replacing spaces
            url = "http://www.songmeanings.net/query/?q=" + title + "&type=songs";
            url = url.Replace(" ", "%20");

            Thread t = new Thread(new ThreadStart(performSearch));
            t.Start();
        }

        private void performSearch()
        {
            String searchPage;

            // fetch page specified by URL
            searchPage = fetchPage();

            // parse html for correct track and retrieve lyrics
            form.changeDisplay(parseLyrics(parseSearch(searchPage)));

        }

        private String parseSearch(String page) 
        {
            String link = "http://www.songmeanings.net/songs/view/";
            String linkTag = "<a href=\"" + link;
            String strongTag = "<strong>";
            String endStrongTag = "</strong>";
            String delim = " - ";
            int pos;
            String result;
            String followLink;

            for (pos=page.IndexOf(linkTag); pos!= 1; pos=page.IndexOf(linkTag))
            {
                followLink = "";

                // Find first link
                pos = page.IndexOf(linkTag);

                // Return if no results found
                if (pos == -1)
                    return null;

                // Consume up to link and find strongTag
                page = page.Substring(pos);
                pos = page.IndexOf(strongTag);
                url = link + page.Substring(linkTag.Length, pos - linkTag.Length - 3);

                // Consume through strongTag and find endStrongTag
                page = page.Substring(pos + strongTag.Length);
                pos = page.IndexOf(endStrongTag);

                // Extract first result
                result = page.Substring(0, pos);

                // Check result to requested song
                result = result.Replace(", The", "");
                artist = artist.Replace("The ", "");

                pos = result.IndexOf(delim);
                if (artist.Equals(result.Substring(0,pos), StringComparison.OrdinalIgnoreCase))
                    if (title.Equals(result.Substring(pos + delim.Length), StringComparison.OrdinalIgnoreCase))
                        return fetchPage();

                // Consume comments
                pos = page.IndexOf(linkTag);
                page = page.Substring(pos + linkTag.Length);
            }
                
            return null;
        }

        private String parseLyrics(String page)
        {
            String lyricsTag = "<!-- end ringtones -->";
            String endLyricsTag = "<!--ringtones and media links -->";
            int pos;
            String lyrics;

            // Check if any matches were made
            if (page == null)
                return "No Results Found!";

            // Fine lyric tag
            pos = page.IndexOf(lyricsTag);

            // Something really wrong
            if (pos == -1)
                return "Page Error!";

            // Consume through lyric tag and find end lyric tag
            page = page.Substring(pos + lyricsTag.Length);
            pos = page.IndexOf(endLyricsTag);

            // Extract lyrics
            return page.Substring(0, pos).Trim().Replace("<br />", "\r\n");
        }

        private String fetchPage()
        {
            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            // execute the request
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // get html result
            byte[] buf = new byte[10000];
            Stream resStream = response.GetResponseStream();

            string tempString = null;
            int count = 0;
            String page = "";

            do
            {
                // fill the buffer with data
                count = resStream.Read(buf, 0, buf.Length);

                // make sure we read some data
                if (count != 0)
                {
                    // translate from bytes to ASCII text
                    tempString = Encoding.ASCII.GetString(buf, 0, count);

                    // continue building the string
                    page += tempString;
                }
            }
            while (count > 0); // any more data to read?

            return page;
        }
    }
}
